<template>
  <div class="app-container flex-col" v-loading="pageLoading">
    <div class="p-20">
      <el-row :gutter="30">
        <el-col :span="12">
          <line-group :functionName="functionName" :data="initData" @onClear="onClearGroupOrEmp"
            @onChange="checkLineGroup"></line-group>
        </el-col>
        <el-col :span="12">
          <emp-scan :data="initData" :focus.sync="empFocus" @onClear="onClearGroupOrEmp" @onChange="afterScanEmp">
          </emp-scan>
        </el-col>
      </el-row>
    </div>
    <div class="p-20 z-border-t">
      <div class="flex flex-center">
        <span class="mr-20">请扫描条码</span>
        <el-input class="flex1 z-scan" v-model="scanData" ref="scan" @keyup.enter.native="afterScan" size="large"
          :disabled="!canScan"></el-input>
      </div>
    </div>
    <div class="flex1 flex z-border-t" style="overflow-x: hidden; overflow-y: auto;">
      <div class="p-20 z-panel z-border-r" style="width: 40%;">
        <div class="z-panel-title">已扫序号历史记录</div>
        <div class="z-panel-body">
          <el-table :data="snHistory" border :show-header="false">
            <el-table-column label="序号">
              <template slot-scope="scope">
                <span :class="scope.row.ec?'text-red':'text-green'">{{scope.row.sn}}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="z-panel p-20 flex1" style="width: 60%;">
        <div class="z-panel-title">当前已扫描不良代码</div>
        <div class="z-panel-body">
          <el-table :data="errorCodes" border style="width: 100%" :show-header="!!errorCodes.length"
            row-class-name="text-red">
            <el-table-column prop="error_code" label="不良代码"> </el-table-column>
            <el-table-column prop="error_name" label="不良名称"> </el-table-column>
            <el-table-column prop="sn" label="序号" v-if="bindCode"> </el-table-column>
            <el-table-column prop="cnt" label="数量"> <template slot-scope="scope">
                <el-input-number :disabled="!!bindCode" v-model="errorCodes[scope.$index].cnt" :min="1" :max="10"
                  label=""></el-input-number>
              </template></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <message-box :msgs="msgs"></message-box>
  </div>
</template>

<script>
import lineGroup from '@/components/WinClient/lineGroup'
import empScan from '@/components/WinClient/empScan'
import messageBox from '@/components/WinClient/messageBox'
import mixinClient from '@/views/_common/mixinClient'
import dayjs from 'dayjs'
import _ from 'lodash'
export default {
  name: 'passNormal',
  mixins: [mixinClient],
  components: { lineGroup, empScan, messageBox },
  data() {
    return {
      pageLoading: false,
      lineOptions: [],
      groupOptions: [],
      initData: {
        line: '',
        group: '',
        emp: '',
        empName: '',
      },
      empFocus: false,
      scanData: '',
      scanMatData: '',
      matScanShow: false,
      msgs: [],
      snHistory: [],
      errorCodes: [],
      matNeeds: [],
      ngNum: '',
      bindCode: '', // 拼板code
      scanTimes: 0, //扫描次数
    }
  },
  methods: {
    checkLineGroup() {
      if (!this.initData.line) return this.showMessage('请选择线别')
      if (!this.initData.group) return this.showMessage('请选择工站')
      this.checkEmp()
    },
    checkEmp() {
      if (!this.initData.empName) {
        this.showMessage('请扫描作业员')
        this.empFocus = true
        return
      } else {
        this.afterScanEmp(true)
      }
    },
    afterScanEmp(r) {
      if (r) {
        this.showMessage('请继续扫描序号或不良代码', false)
        setTimeout(() => {
          this.$refs.scan.focus()
        }, 200)
      } else {
        this.showMessage('作业员不正确', true)
      }
    },
    afterScan() {
      this.scanData = this.scanData.trim()
      if (!this.scanData) {
        this.showMessage('没有扫描到任何内容', true)
        return
      }
      this.scanData = this.scanData.toUpperCase()
      if (this.scanData == 'UNDO') {
        this.undo()
        return
      }
      if (this.scanData == 'END') {
        if (this.bindCode && this.scanTimes % 2 == 0) {
          this.passStation()
          return
        } else {
          this.showMessage('扫描错误，请扫描序号/或不良代码', true)
          return
        }
      }

      if (this.scanData == 'END' && this.bindCode && this.scanTimes % 2 == 0) {
        this.passStation()
        return
      }
      if (this.scanData == 'END' && this.scanTimes % 2 != 0) this.matNeeds = []
      this.pageLoading = true
      this.scanTimes += 1
      this.$request(this.$api.errorCode + 'check', { error_code: this.scanData.trim() }, 'get', true)
        .then((r) => {
          this.pageLoading = false
          if (r) {
            //识别到不良代码
            let errorExist = this.bindCode
              ? true
              : _.findIndex(this.errorCodes, (i) => i.error_code == this.scanData) == -1
            if (errorExist) {
              //拼板，扫一次不良代码，扫一次序号。
              if (this.bindCode && this.scanTimes % 2 == 0) throw new Error('扫描错误:当前拼板扫不良，请扫描产品序号。')
              this.errorCodes.push({ ...r, cnt: 1, sn: null })
              this.showMessage(
                this.bindCode
                  ? '当前为拼板扫不良，不良代码扫描成功，请继续扫描序号。'
                  : '不良代码扫描成功，请继续扫描不良代码或者序号。',
                false,
              )
            } else {
              throw new Error('不良代码扫描重复')
            }
            setTimeout(() => {
              this.$refs.scan.select()
            }, 200)
          } else {
            //未识别到不良代码 检查序号和流程
            this.$request(
              this.$api.baseUrl + 'Mes/wip/checksnroute',
              {
                group: this.initData.group,
                sn: this.scanData,
                error_flag: this.errorCodes.length > 0 ? '1' : '0',
                reply: true,
              },
              'post',
              true,
            )
              .then((r) => {
                this.pageLoading = false
                if (r.pickups.length > 0) throw new Error('此页面不支持扫描物料。')

                //单体数量检查
                if (this.errorCodes.length > 0 && r.wips.length == 1 && r.wips[0].sn_batch_qty == 1) {
                  if (_.findIndex(this.errorCodes, (i) => i.cnt > 1) > -1)
                    throw new Error('扫描错误:单体不良产品数必须是1')
                }
                //拼板检查
                if (r.wips.length > 1) {
                  if (this.errorCodes.length > 0) {
                    if (this.errorCodes.filter((v) => !v.sn).length > 1)
                      throw new Error('拼板序号扫不良，只支持扫一次不良，扫一次序号，请扫描UNDO清空，重新扫描。')
                    if (!this.bindCode) {
                      this.bindCode = r.wips[0].bind_code
                    } else {
                      if (this.bindCode != r.wips[0].bind_code)
                        throw new Error('扫描错误:当前拼板扫不良，产品序号必须是同一个拼板')
                    }

                    if (this.scanTimes % 2 != 0 && this.scanData.toUpperCase() != 'END')
                      throw new Error('扫描错误:当前拼板扫不良，请扫描不良代码或END结束')
                    if (
                      _.findIndex(
                        this.errorCodes,
                        (i) =>
                          i.sn == this.scanData && i.error_code == this.errorCodes[this.scanTimes / 2 - 1].error_code,
                      ) > -1
                    )
                      throw new Error('扫描错误:当前拼板扫不良，相同序号，不良代码已经存在。')

                    if (_.findIndex(this.errorCodes, (i) => i.cnt > 1) > -1)
                      throw new Error('扫描错误:拼板不良产品数必须是1')

                    if (this.scanTimes % 2 == 0) this.errorCodes[this.scanTimes / 2 - 1].sn = this.scanData

                    if (this.scanData != 'END') {
                      setTimeout(() => {
                        this.$refs.scan.select()
                      }, 200)
                      this.showMessage('当前拼板扫不良,请继续扫描不良代码或END结束。', false)
                      return
                    }
                  }
                }
                if (this.bindCode) throw new Error('扫描错误:当前是拼板扫不良，请继续扫描不良代码或END结束。')
                this.passStation()
              })
              .catch((e) => {
                this.pageLoading = false
                this.scanTimes -= 1
                //序号和流程检查失败
                setTimeout(() => {
                  this.$refs.scan.select()
                }, 200)
                this.showMessage(e.message, true)
              })
          }
        })
        .catch((e) => {
          this.pageLoading = false
          this.scanTimes -= 1
          setTimeout(() => {
            this.$refs.scan.select()
          }, 200)
          this.showMessage(e.message, true)
        })
    },
    passStation() {
      this.pageLoading = true
      this.$request(
        this.$api.baseUrl + 'Mes/wip/passstation',
        {
          line: this.initData.line,
          group: this.initData.group,
          emp: this.initData.emp,
          sn: this.scanData.toUpperCase() == 'END' ? this.errorCodes[0].sn : this.scanData,
          ec: this.errorCodes.map((i) => ({
            error_code: i.error_code,
            cnt: i.cnt,
            sn: i.sn,
          })),
        },
        'POST',
        true,
      )
        .then((r) => {
          this.pageLoading = false
          this.afterPassStation(
            this.scanData,
            '[ ' + this.scanData + ' ]过站成功，请扫描下一产品序号',
            this.errorCodes.length > 0 ? true : false,
          )
        })
        .catch((e) => {
          this.pageLoading = false
          setTimeout(() => {
            this.$refs.scanData.select()
          }, 200)
          this.showMessage(e.message, true)
          this.scanTimes -= 1
        })
    },
    onClearGroupOrEmp() {
      this.clearScanData()
      this.checkLineGroup()
    },
    undo() {
      this.clearScanData()
    },
    clearScanData() {
      this.scanData = ''
      this.scanMatData = ''
      this.errorCodes = []
      this.matNeeds = []
      this.scanTimes = 0
      this.bindCode = ''
    },
    afterPassStation(sn, msg, errorCodeFlag) {
      if (sn.toUpperCase() == 'END' && this.errorCodes[0].sn) {
        this.errorCodes.forEach((v) => {
          this.snHistory.unshift({ sn: v.sn, ec: !!errorCodeFlag, time: dayjs().format('HH:mm:ss') })
        })
      } else {
        this.snHistory.unshift({ sn, ec: !!errorCodeFlag, time: dayjs().format('HH:mm:ss') })
      }

      this.showMessage(msg, false)
      this.clearScanData()
      setTimeout(() => {
        this.$refs.scan.focus()
      }, 200)
    },
  },
  computed: {
    canScan: function () {
      return this.initData.line && this.initData.group && this.initData.empName
    },
    canSelectLineAndGroup: function () {
      return !this.initData.line || !this.initData.group
    },
    canInputEmp: function () {
      return !this.initData.empName && this.initData.line && this.initData.group
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/styles/client.scss';
</style>
